//----------------------------------------------------------------
// Start of stefanwill swSort code in top javascript
//
// Copyright Stefan Will, 2011, All Rights Reserved
// Limited permission is granted to use this code on Smugmug
// Version 0.2
//----------------------------------------------------------------


//**************************************************
//***swSortIntoSections
//***
//***This is the main method for sorting. It first
//***verifies if the category/sub category is relevant
//***for sorting. Then sorting is done by using
//***several AJAX calls.
//***Note: When async AJAX calls are made the processing
//***      normally goes on in the callback function
//***      of the AJAX call
//**************************************************
function swSortIntoSections(){
  
  if (swSortConstants.verbose == true){
    console.log("swSortIntoSections");
  }
  
  //alert("hello");

  //first check if we have something to do
  //find out current category
  var curr_cat = swGetCurrCategory();
  if (swSortConstants.verbose == true){
    console.log("info: Current Category is: " + curr_cat);
  }
  var curr_subcat = swGetCurrSubCategory();
  if (swSortConstants.verbose == true){
    console.log("info: Current Sub Category is: " + curr_subcat);
  }
  
  //find out if the category is relevant for sorting
  if (curr_subcat == "no subcategory"){
    curr_subcat = "";
  }
  var cat_rel_for_sort = swIsCategoryRelevantForSorting(curr_cat, curr_subcat);
  if (swSortConstants.verbose == true){
    console.log("info: relevant for sorting: " + cat_rel_for_sort);
  }
  
  
  //extra check for Homepage categoriesBox
  if ($('#categoriesBox').length > 0){
    //only if the body tag contains the galleries class we are at the
    //galleries-screen. If the galleries class is not present we are at the
    //slideshow start screen and should not do anything
    if ($('body').hasClass('galleries')){
      if (swSortConstants.verbose == true){
        console.log("there is a categoriesBox and it has the galleries class");
      }
      cat_rel_for_sort = true;
      curr_cat = "home_categoriesBox";
      if (swSortConstants.verbose == true){
        console.log("setting current category (curr_cat) to: " + curr_cat);    
      }
    }
  }


  //extra check for Homepage galleriesBox
  console.dir($('#homepageBoxes > #galleriesBox'));
  if ($('#homepageBoxes > #galleriesBox').length > 0){
    //only if the body tag contains the galleries class we are at the
    //galleries-screen. If the galleries class is not present we are at the
    //slideshow start screen and should not do anything
    if ($('body').hasClass('galleries')){
      if (swSortConstants.verbose == true){
        console.log("there is a galleriesBox and it has the galleries class");
      }
      cat_rel_for_sort = true;
      curr_cat = "home_galleriesBox";
      if (swSortConstants.verbose == true){
        console.log("setting current category (curr_cat) to: " + curr_cat);    
      }
    }
  }

  
  
  if (cat_rel_for_sort == true){
    //category seems to be relevant for sorting
    //so we start...
    
    //first remember the current category and sub category
    swSort.curr_category = curr_cat;
    swSort.curr_subcategory = curr_subcat;
    
    if (swSortConstants.verbose == true){
      console.log("start sorting into sections...");
    }
    
    var subcat = swGetSubCategoriesByCategory(curr_cat);
    //console.dir(subcat);
    if (subcat != null){
      if (swSortConstants.verbose == true){
        console.log("info: " + subcat.length + " sub categories found");
      }
    } else {
      console.log("warning: subcat null");
    }
    
    
    //make an ajax call to create the Sorted Box
    //as this makes internally an async call the coding/processing goes on in
    //the ajax calls callback function
    swCreateSortedBoxByJSON();
    
  }
  
  
}



//**************************************************
//***swCreateSortedBoxByJSON
//***
//***This function creates a new box, and moves the
//***miniBoxes into it in the sequence defined in
//***the JSON settings
//**************************************************
function swCreateSortedBoxByJSON(){

  //get a session ID using an AJAX call
  //first try to login with session
  $.getJSON("/services/api/json/1.2.2/?method=smugmug.login.withSession&APIKey=b65LbayWryydERbvo9mwPLC6bkr7DJ8s",
    {
  
    },
    function(data) {
      //This is the callback function where we go on with processing
      if (swSortConstants.verbose == true){
        console.log("info: API call " + data.method + " " + data.stat);
      }
      if (data.stat === "ok"){
        //console.log("The Session ID is " + data.Login.Session.id);
      }
  
      //if the login withSession was not successfully we login anonymously as fallback
      if (data.stat.toLowerCase() === "fail"){
        if (swSortConstants.verbose == true){
          console.log("login failed...trying anonymous login...");
        }
        //we login anonymously sync because the album_fetch function shall not start before
        //the login call is finished
        swLogin_anonymously_sync();
      }
      
      //before reading the json customizing we need to determine the
      //gallery id/key which contains the json. This can be different
      //for each category/sub category
      var json_gallery = swSortGetSectionJSONGalleryByCategory(swSort.curr_category, swSort.curr_subcategory);
      if (swSortConstants.verbose == true){
        console.log("json_gallery found for " + swSort.curr_category + " / " + swSort.curr_subcategory);
        console.dir(json_gallery);
      }
      
      //now make another ajax call to get the sort customizing
      //This time the call can be synchroneous because we are already in an async call
      if (swSortConstants.verbose == true){
        console.log("info: reading section customizing from gallery " + json_gallery.json_gallery_id + " / " + json_gallery.json_gallery_key);
      }
      
      var sub_section_json = swGetGalleryJSONAsync(json_gallery.json_gallery_id, json_gallery.json_gallery_key);
      if (swSortConstants.verbose == true){
        console.dir(sub_section_json);
      }
      
      //console.log("swSort.curr_category: " + swSort.curr_category);
      //console.log("swSort.curr_subcategory: " + swSort.curr_subcategory);
      
      //from the json we read the settings for the current category / sub category
      var settings_found = false;
      for (idx in sub_section_json){
        console.log("sub_section_json[idx].category: " + sub_section_json[idx].category);
        console.log("sub_section_json[idx].subcategory: " + sub_section_json[idx].subcategory);
        console.log("swSort.curr_category: " + swSort.curr_category);
        console.log("swSort.curr_subcategory: " + swSort.curr_subcategory);
        if (swSort.curr_category == sub_section_json[idx].category &&
            swSort.curr_subcategory == sub_section_json[idx].subcategory ) {
          
          settings_found = true;
          
          //***use the settings and call the function which creates the sorted box
          var settings = sub_section_json[idx].settings;
          swCreateSortedBox(settings);
          
          if (sub_section_json[idx].settings.hide_empty_sections != null){
            if (sub_section_json[idx].settings.hide_empty_sections == "true"){
              
              if (swSortConstants.verbose == true){
                console.log("info: hiding empty sections (if there are any)...");
              }
              swHideEmptySections();
              
            } else {
              if (swSortConstants.verbose == true){
                console.log("parameter hide_empty_sections tells not to hide (value: " +
                             sub_section_json[idx].settings.hide_empty_sections +
                            ")");
              }
            }
          } else {
            if (swSortConstants.verbose == true){
              console.log("info: parameter hide_empty_sections not provided");
            }
          } //end of if hide_empty_sections
          
          
          //***hide original galleries box
          if (sub_section_json[idx].settings.hide_original_galleries_box_if_empty != null){
            if (sub_section_json[idx].settings.hide_original_galleries_box_if_empty == "true"){
              
              if (swSortConstants.verbose == true){
                console.log("info: hiding original galleriesBox if empty...");
              }
              swHideOriginalGalleriesBoxIfEmpty();
              
            } else {
              if (swSortConstants.verbose == true){
                console.log("parameter hide_original_galleries_box_if_empty tells not to hide (value: " +
                             sub_section_json[idx].settings.hide_original_galleries_box_if_empty +
                            ")");
              }
            }
          } else {
            if (swSortConstants.verbose == true){
              console.log("info: parameter hide_original_galleries_box_if_empty not provided");
            }
          } //end of if hide_original_galleries_box_if_empty
          
          
          //***hide original subcategories box
          if (sub_section_json[idx].settings.hide_original_subcat_box_if_empty != null){
            if (sub_section_json[idx].settings.hide_original_subcat_box_if_empty == "true"){
              
              if (swSortConstants.verbose == true){
                console.log("info: hiding original subcategoriesBox if empty...");
              }
              swHideOriginalSubcatBoxIfEmpty();
              
            } else {
              if (swSortConstants.verbose == true){
                console.log("parameter hide_original_subcat_box_if_empty tells not to hide (value: " +
                             sub_section_json[idx].settings.hide_original_subcat_box_if_empty +
                            ")");
              }
            }
          } else {
            if (swSortConstants.verbose == true){
              console.log("info: parameter hide_original_subcat_box_if_empty not provided");
            }
          } //end of if hide_original_subcat_box_if_empty
          
        }
      }
      
      if(settings_found == false){
        console.log("error: no settings found for category '" + 
                    swSort.curr_category + 
                    "' / sub category '" + 
                    swSort.curr_subcategory + 
                    "'" + 
                    " but it is defined as relevant for sorting.");
      }
      

  
  }); //end of getJSON login.withSession callback function

}
//**************************************************
//*** end of swCreateSortedBoxByJSON
//**************************************************




//**************************************************
//*** swCreateSortedBox
//***
//*** this function creates a new div like the divs
//*** for gallery and sub category thumbs. This new
//*** div contains other divs for each section which
//*** is define in the json object passed in parameter
//*** sub_section_json
//***
//*** After creating the div(s) the miniBoxes of the
//*** page are moved from their original boxes to
//*** the sorted box and into their respective section
//**************************************************
function swCreateSortedBox(sub_section_json){

  //console.log("sub_section_json before sort");
  //console.dir(sub_section_json);
  
  //first sort the definitions by sequence_id
  sub_section_json.section_definitions.sort(swSortBySequenceID);
  
  //now sort the assignements by sequence_id
  sub_section_json.section_assignements.sort(swSortBySequenceID);
  
  //console.log("sub_section_json after sort");
  //console.dir(sub_section_json);
  
  var YD = YAHOO.util.Dom;

  var sub_section_defs = sub_section_json.section_definitions;
  //console.dir(sub_section_defs);

  //get the category element
  var category = $('#category');

  var homepageTools = $('#breadcrumb');
  
  homepageTools.after('<div id="sectionBox"></div>');
  //category.prepend('<div id="sectionBox"></div>');
  
  var sectionBox = $('#sectionBox');
  sectionBox.addClass('box');
  //console.dir(sectionBox);

  sectionBox.append('<div id="sectionBoxTop"></div>');
  var sectionBoxTop = $('#sectionBoxTop');
  sectionBoxTop.addClass('boxTop');
  
  //get the title for the sorted box
  var section_box_title = sub_section_json.title;
  
  sectionBoxTop.append('<h3 id="sectionBoxTitle">' + section_box_title + '</h3>');
  var sectionBoxTitle = $('#sectionBoxTitle');
  sectionBoxTitle.addClass('title');
  sectionBoxTitle.addClass('notopmargin');
  
  sectionBox.append('<div id="sectionBoxBottom"></div>');
  var sectionBoxBottom = $('#sectionBoxBottom');
  sectionBoxBottom.addClass('boxBottom');
  
  //*** create the boxSettings if we are logged in
  if ($('body').hasClass("loggedIn")){
    sectionBoxTop.append('<span>&nbsp;|&nbsp;<a href="' + swSortConstants.org_link + '">organize sections</a></span>');
  }
  
  //*** create the sections according to the section_definitions
  for (i=0; i<sub_section_defs.length; i++){
    var curr_def = sub_section_defs[i];
    
    //console.dir(curr_def);
    
    var new_div = '<div id="' + curr_def.section_id + '"></div>';
    sectionBoxBottom.append(new_div);

    var curr_section = $('#' + curr_def.section_id);
    curr_section.addClass('section');
    
    //the first section gets an additional class
    if (i == 0){
      curr_section.addClass('firstSection');
    }
    
    //add the boxTop which will contain the section header
    curr_section.append('<div class="boxTop"></div>');
    var curr_section_box_top = $('#' + curr_def.section_id + ' > .boxTop');
    curr_section_box_top.addClass('catSectionHeader');
    //at the first section we add another class
    if (i == 0){
      curr_section_box_top.addClass('firstCatSectionHeader');
    }
    
    curr_section_box_top.append('<h3 id="sectionTitle_' + curr_def.section_id + '">' + curr_def.section_text + '</h3>');
    var section_box_section_title = $('#sectionTitle_' + curr_def.section_id);
    section_box_section_title.addClass('sectionTitle');
    //section_box_section_title.addClass('title');
    section_box_section_title.addClass('notopmargin');
    
    
    //add the boxBottom which will be the container for the miniBoxes
    curr_section.append('<div class="boxBottom"></div>');
    var curr_section_box_bottom = curr_section.children('.boxBottom');
    curr_section_box_bottom.addClass('catSectionBoxBottom');
    //at the first section we add another class
    if (i == 0){
      curr_section_box_bottom.addClass('firstCatSectionBoxBottom');
    }
  }
  
  //*** create the unsorted section
  //*** this section is only created here. It is filled with the remaining miniBoxes at the end of processing
  if (sub_section_json.create_unsorted_section == "true"){
    
    var new_div = '<div id="other"></div>';
    sectionBoxBottom.append(new_div);
    
    var curr_section = $('#other');
    
    curr_section.addClass('section');
    
    curr_section.append('<div class="boxTop"></div>');
    var curr_section_box_top = $('#other > .boxTop');
    curr_section_box_top.append('<h3 id="sectionTitle_other">Other</h3>');
    curr_section_box_top.addClass('catSectionHeader');
    var curr_section_title = $('#sectionTitle_other');
    //curr_section_title.addClass('title');
    section_box_section_title.addClass('sectionTitle');
    curr_section_title.addClass('notopmargin');
    
    curr_section.append('<div class="boxBottom"></div>');
    var curr_section_box_bottom = curr_section.children('.boxBottom');
    curr_section_box_bottom.addClass('catSectionBoxBottom');
  }
  
  //*** at this point the section divs are created but they are empty
  //*** up to now
  
  //now create IDs for gallery and sub category miniBoxes
  swSetGalleryMiniBoxIDs();
  swSetSubcategoryMiniBoxIDs();
  swSetCategoryMiniBoxIDs();
  
  //*** now we start moving the miniBoxes to the sorted box
  
  if (swSortConstants.verbose == true){
    console.log("info: starting to move miniBoxes");
  }
  //console.dir(sub_section_json.section_assignements);
  var sub_section_asg = sub_section_json.section_assignements;
  
  //now start to move the miniBoxes to the sorted box
  //To do this we go through the sub_section_json.section_assignements
  //and find and move the corresponding boxes. To find the miniBoxes
  //we can use the IDs we derived before
  for(i=0; i<sub_section_asg.length; i++){
    
    var curr_asg = sub_section_asg[i];
    if (swSortConstants.verbose == true){
      console.log("info: current assignement: ");
      console.dir(curr_asg);
    }
    
    //find the miniBox specified in the current assignement
    //depending if the current miniBox is a gallery or sub category
    //different keys are used in the json. So we need to be
    //prepared that keys might not be provided

    //************
    //category
    //in this case we expect key subcat_id
    if (curr_asg.category_id != null){
      if (curr_asg.category_id != ""){
        
        //console.log("category_id specified: " + curr_asg.category_id);
        //try to find the specified cat miniBox in the DOM
        var cat_box = $('#cat_' + curr_asg.category_id);
        
        if (cat_box.length > 0){
        
          if (swSortConstants.verbose == true){
            console.log("category found: " + curr_asg.category_id);
          }
          //now find the specified target section
          if (curr_asg.section_id != null){
            //console.log("curr_asg.section_id is: " + curr_asg.section_id);
            var target_section = $('#' + curr_asg.section_id + ' > .boxBottom');
            if (target_section.length > 0){
            
              if (swSortConstants.verbose == true){
                console.log("section_id: " + curr_asg.section_id);
              }
              //now move the miniBox to the target section
              target_section.append(cat_box);
              
            } else {
              console.log("error: section_id not found in DOM: " + curr_asg.section_id);
            }
          } else {
            console.log("error: no section_id specified (key in JSON missing).");
          }
        
        } else {
          console.log("error: specified category not found: " + curr_asg.category_id);
        }
        
      } else {
        //console.log("info: category_id found but empty (not a problem).");
      }
    } else {
      //console.log("info: no category parameter provided (not a problem).");
    } //end of if subcat_id not provided
    //***

    //************
    //sub category
    //in this case we expect key subcat_id
    if (curr_asg.subcat_id != null){
      if (curr_asg.subcat_id != ""){
        
        //console.log("subcat_id specified: " + curr_asg.subcat_id);
        //try to find the specified subcat miniBox in the DOM
        var subcat_box = $('#subcat_' + curr_asg.subcat_id);
        if (subcat_box.length > 0){
        
          if (swSortConstants.verbose == true){
            console.log("sub category found: " + curr_asg.subcat_id);
          }
          //now find the specified target section
          if (curr_asg.section_id != null){
            var target_section = $('#' + curr_asg.section_id  + ' > .boxBottom');
            if (target_section.length > 0){
            
              if (swSortConstants.verbose == true){
                console.log("section_id: " + curr_asg.section_id);
              }
              //now move the miniBox to the target section
              target_section.append(subcat_box);
              
            } else {
              console.log("error: section_id not found in DOM: " + curr_asg.section_id);
            }
          } else {
            console.log("error: no section_id specified (key in JSON missing).");
          }
        
        } else {
          console.log("error: specified sub category not found: " + curr_asg.subcat_id);
        }
        
      } else {
        //console.log("info: subcat_id found but empty (not a problem).");
      }
    } else {
      //console.log("info: no sub category parameter provided (not a problem).");
    } //end of if subcat_id not provided
    //***
    
    //*******
    //gallery
    //in this case we expect the gallery_id
    if (curr_asg.gallery_id != null){
      
      if (curr_asg.gallery_id != ""){
        
        //console.log("gallery specified: " + curr_asg.gallery_id);
        //try to find the specified gallery miniBox in the DOM
        var search_id = "gallery_" + curr_asg.gallery_id;
        var gallery_box = $('#' + search_id);
        if (gallery_box.length > 0){
        
          if (swSortConstants.verbose == true){
            console.log("info: gallery found: " + curr_asg.gallery_id);
          }
          //now find the specified target section
          if (curr_asg.section_id != null){
            var target_section = $('#' + curr_asg.section_id + ' > .boxBottom');
            if (target_section.length > 0){
            
              //console.log("section_id: " + curr_asg.section_id);
              //now move the miniBox to the target section
              target_section.append(gallery_box);

            } else {
              console.log("error: section_id not found in DOM: " + curr_asg.section_id);
            }
          } else {
            console.log("error: no section_id specified (key in JSON missing).");
          }
        
        } else {
          if (swSortConstants.verbose == true){
            console.log("warning: gallery_box.length is 0. Normal if you are logged off and there are hidden galleries.");
            console.log(" warning: specified gallery not found: " + curr_asg.gallery_id);
            console.log(" warning: search_id was: " + search_id);
          }
        }

      } else {
        console.log("warning: gallery_id found but empty (not a problem)");
      }
    } else {
      //console.log("info: no gallery_id parameter provided (not a problem)");
    } //end of if gallery_id
    //***
    
  } //end of for
  
  //now go over the sections and append a spacer to each one
  //append a spacer to each section
  for(i=0; i<sub_section_defs.length; i++){
    var curr_def = sub_section_defs[i];
    
    var curr_section = $('#' + curr_def.section_id + ' > .boxBottom');
    //console.log(curr_def.section_id);
    curr_section.append('<div class="spacer"></div>');
    
  }
  
  //*** move the remaining miniBoxes to the others section
  if (sub_section_json.create_unsorted_section == "true"){

    var other_section = $('#other > .boxBottom');
    
    //*unsorted categories
    var remaining_category_miniBoxes = $('#categoriesBox > .boxBottom > .miniBox');
    for(i=0; i<remaining_category_miniBoxes.length; i++){
      var curr_miniBox = remaining_category_miniBoxes[i];
      
      other_section.append(curr_miniBox);
      
    }
    if (remaining_category_miniBoxes.length > 0){
      other_section.append('<div class="spacer"></div>');
    }
    
    //*unsorted sub categories
    var remaining_subcat_miniBoxes = $('#subcategoriesBox > .boxBottom > .miniBox');
    for(i=0; i<remaining_subcat_miniBoxes.length; i++){
      var curr_miniBox = remaining_subcat_miniBoxes[i];
      
      other_section.append(curr_miniBox);
      
    }
    if (remaining_subcat_miniBoxes.length > 0){
      other_section.append('<div class="spacer"></div>');
    }
    
    //*unsorted galleries
    var remaining_gallery_miniBoxes = $('#galleriesBox > .boxBottom > .miniBox');
    for(i=0; i<remaining_gallery_miniBoxes.length; i++){

      var curr_miniBox = remaining_gallery_miniBoxes[i];
      other_section.append(curr_miniBox);
      
    }
    if (remaining_gallery_miniBoxes.length > 0){
      other_section.append('<div class="spacer"></div>');
    }
  }
  
} //end of function swCreateSortedBox



//**************************************************
//*** swSortBySequenceID
//***
//***This function expects that a and b each have
//***a field named "sequence_id" filled.
//***a and b are sorted by the sequence id asc.
//***The actual return of the function is
//*** -1 if a.seqence_id is lower than b.sequence_id
//***  1 if a.sequence_id is higher than b.sequence_id
//***  0 if a.sequence_id is equal b.sequence_id
//**************************************************
function swSortBySequenceID(a, b){

  return(a.sequence_id - b.sequence_id);
  
} //end of function swSortBySequenceID




//**************************************************
//*** swSortGetSectionJSONGalleryByCategory
//***
//*** this function determines the gallery in which
//*** the JSON customizing for the current category /
//*** sub category is located
//**************************************************
function swSortGetSectionJSONGalleryByCategory(curr_category, curr_subcategory){

  if (swSortConstants.verbose == true){
    console.log("info: reading customizing gallery for category/subcategory: " + curr_category + " / " + curr_subcategory);
  }
  
  var curr_rel_cat = "";
  var curr_rel_subcat = "";
  var json_gallery = new Object();
  
  for (idx in swSortConstants.relevantCategories){
    
    //console.log("index: " + idx);
    
    if (swSortConstants.relevantCategories[idx].category != null){
      curr_rel_cat = swSortConstants.relevantCategories[idx].category;
    }
    
    if (swSortConstants.relevantCategories[idx].subcategory != null){
      curr_rel_subcat = swSortConstants.relevantCategories[idx].subcategory;
    } else {
      curr_rel_subcat = "";
    }
    
    if (curr_category == curr_rel_cat && curr_subcategory == curr_rel_subcat){

      if (swSortConstants.relevantCategories[idx].json_gallery_id != null &&
          swSortConstants.relevantCategories[idx].json_gallery_key != null){
        
        json_gallery.json_gallery_id = swSortConstants.relevantCategories[idx].json_gallery_id;
        json_gallery.json_gallery_key = swSortConstants.relevantCategories[idx].json_gallery_key;
        
      } else {
        //console.log("json_gallery_id und json_gallery_key null");
      }
    } else {
      //console.log("ungleich");
      //console.log("curr_category: " + curr_category);
      //console.log("curr_rel_cat: " + curr_rel_cat);
      //console.log("curr_subcategory: " + curr_subcategory);
      //console.log("curr_rel_subcat: " + curr_rel_subcat);
    }
    
    //console.log("json_gallery");
    //console.dir(json_gallery);
    
  }
  
  return(json_gallery);
}
//**************************************************
//*** end of swSortGetSectionJSONGalleryByCategory
//**************************************************



//**************************************************
//*** swSetGalleryMiniBoxIDs
//***
//*** this function sets an ID to the gallery
//*** miniBoxes which is build in the following
//*** way: miniBox_AlbumId_AlbumKey
//**************************************************
function swSetGalleryMiniBoxIDs(){

  //determine the miniBoxes
  //var galleryMiniBoxes = $('#category > #galleriesBox > .boxBottom > .miniBox');
  var galleryMiniBoxes = $('#galleriesBox > .boxBottom > .miniBox');
  
  for(i=0; i<galleryMiniBoxes.length; i++){
  	
    //to get a jquery object of the current miniBox simply pass the DOM element in the brackets
    var curr_miniBox = $(galleryMiniBoxes[i]);
    
    //find out the new id (we use the AlbumId_AlbumKey which is used as id in the image tag)
    //we use a prefix before the id to prevent duplicate IDs
    var img_tag = curr_miniBox.find('div > a > img');
    //console.log(img_tag.attr("id"));
    
    //since version 0.2 we only need the gallery_id (not the gallery key)
    var gallery_id = img_tag.attr("id").substring(0, img_tag.attr("id").indexOf("_"));
    
    //set the id of the img_tag as id of the 
    var miniBox_id = "gallery_" + gallery_id;
    curr_miniBox.attr("id", miniBox_id);

  
  }

}
//**************************************************
//*** end of swSetGalleryMiniBoxIDs
//**************************************************



//**************************************************
//*** swSetSubcategoryMiniBoxIDs
//***
//*** this function sets an ID to the gallery
//*** miniBoxes which is build in the following
//*** way: miniBox_AlbumId_AlbumKey
//**************************************************
function swSetSubcategoryMiniBoxIDs(){

  //determine the miniBoxes
  //var galleryMiniBoxes = $('#category > #galleriesBox > .boxBottom > .miniBox');
  var subcatMiniBoxes = $('#category > #subcategoriesBox > .boxBottom > .miniBox');
  
  for(i=0; i<subcatMiniBoxes.length; i++){
  	
    //to get a jquery object of the current miniBox simply pass the DOM element in the brackets
    var curr_miniBox = $(subcatMiniBoxes[i]);
    
    var a_tag = curr_miniBox.find('div > a');
    //console.log(a_tag.attr("href"));
    
    var a_href = a_tag.attr("href");
    var slash_index = a_href.lastIndexOf("/");
    var subcat_name = a_href.substring(slash_index + 1);
    //console.log(subcat_name);
    
    //set the sub category name as ID using a prefix subcat
    curr_miniBox.attr("id", "subcat_" + subcat_name);    

  }

}
//**************************************************
//*** end of swSetSubcategoryMiniBoxIDs
//**************************************************



//**************************************************
//*** swSetCategoryMiniBoxIDs
//***
//*** this function sets an ID to the gallery
//*** miniBoxes which is build in the following
//*** way: miniBox_AlbumId_AlbumKey
//**************************************************
function swSetCategoryMiniBoxIDs(){

  //determine the miniBoxes
  //var galleryMiniBoxes = $('#category > #galleriesBox > .boxBottom > .miniBox');
  var catMiniBoxes = $('#categoriesBox > .boxBottom > .miniBox');
  
  for(i=0; i<catMiniBoxes.length; i++){
  	
    //to get a jquery object of the current miniBox simply pass the DOM element in the brackets
    var curr_miniBox = $(catMiniBoxes[i]);
    
    var a_tag = curr_miniBox.find('div > a');
    //console.log(a_tag.attr("href"));
    
    var a_href = a_tag.attr("href");
    var slash_index = a_href.lastIndexOf("/");
    var cat_name = a_href.substring(slash_index + 1);
    //console.log(cat_name);
    
    //set the sub category name as ID using a prefix subcat
    curr_miniBox.attr("id", "cat_" + cat_name);    

  }

}
//**************************************************
//*** end of swSetCategoryMiniBoxIDs
//**************************************************



//**************************************************
//***swLogin_anonymously_sync
//***
//***This method calls the login.anonymously method
//***sync (default would be async)
//***calls start before the login is finished
//***This function can be used if follow up function
//**************************************************
function swLogin_anonymously_sync(){
  var url = "/services/api/json/1.2.2/?method=smugmug.login.anonymously&APIKey=b65LbayWryydERbvo9mwPLC6bkr7DJ8s";
  $.ajax({  
    url: url,  
    dataType: 'json',  
    async: false,  
    success: function(json){  
                    //success code  
      if (swSortConstants.verbose == true){
        console.log("login_anonymously2");
        console.log("API call " + json.method + " " + json.stat);
        console.log("The Session ID is " + json.Login.Session.id);
      }
                 },
    error: function(){
      console.log("error: anonymous login failed.");
    }
  });
}
//**************************************************
//*** end of swLogin_anonymously_sync
//**************************************************



function swGetGalleryJSONAsync(gallery_id, gallery_key){
  
  var url = "/services/api/json/1.2.2/?method=smugmug.albums.getInfo&AlbumID=" + gallery_id + "&AlbumKey=" + gallery_key + "&NickName=" + swSortConstants.nickname;
  if (swSortConstants.verbose == true){
    console.log("info: API call to get section json.");
  }
  var gallery_desc = $.ajax({  
    url: url,  
    dataType: 'json',  
    async: false,  
    success: function(json){  
      //success code  
      return("rueckgabewert1");
    },
    error: function(){
      console.log("error: API albums.get call failed.");
    }
  });  
  //console.dir(ret);

  var response_json = $.parseJSON(gallery_desc.responseText);

  //console.log(response_json.Album.Description);

  try {
    response_json = $.parseJSON(response_json.Album.Description);
  } catch(e) {
    console.log("error: parsing gallery JSON failed. Normally this indicates syntactial mistakes in the JSON.");
    //ErrorHandler.handleError(e);
  }

  //console.dir(response_json);

  return(response_json);
}
//**************************************************
//*** end of swGetGalleryJSONAsync
//**************************************************




//**************************************************
//*** swGetCurrCategory
//***
//*** determines the current category name
//**************************************************
function swGetCurrCategory(){

  var category_name = "no category";

  var jq_category = $('#category');
  
  if (jq_category.hasClass('category')){
    //console.log("we found a category");
    var jq_class = jq_category.attr('class');
    //console.log(jq_class);
    //get the category name of the accoring class
    var cat_start_idx = jq_class.indexOf("category_");
    jq_class = jq_class.substring(cat_start_idx);
    //console.log(jq_class);
    var cat_end_idx = jq_class.indexOf(" ");
    jq_class = jq_class.substring(0, cat_end_idx);
    //console.log(jq_class);
    jq_class = jq_class.substring(9);
    //console.log(jq_class);
    
    category_name = jq_class;
  }


  /*
  //this coding determines the category in gallery detail views too
  var jq_category = $('body');
  var jq_class = jq_category.attr('class');
  
  if (jq_class.indexOf("category_") > -1){
    console.log("we found a category");
    
    console.log(jq_class);
    //get the category name of the accoring class
    var cat_start_idx = jq_class.indexOf("category_");
    jq_class = jq_class.substring(cat_start_idx);
    console.log(jq_class);
    var cat_end_idx = jq_class.indexOf(" ");
    jq_class = jq_class.substring(0, cat_end_idx);
    console.log(jq_class);
    jq_class = jq_class.substring(9);
    console.log(jq_class);
    
    category_name = jq_class;
  }
  */
  
  return(category_name);
}
//**************************************************
//*** end of swGetCurrCategory
//**************************************************


//**************************************************
//*** swGetCurrSubCategory
//***
//*** determines the current subcategory name
//**************************************************
function swGetCurrSubCategory(){

  var subcategory_name = "no subcategory";

  /*
  var YD = YAHOO.util.Dom;
  
  //var bc_div = document.getElementById("breadCrumbTrail");
  //YD.addClass(new_a, "nav");
  //YD.insertBefore(new_a, a_tags[index]);
  //YD.insertAfter(new_a, a_tags[index]);
  //YD.hasClass(body, gallery_class)
  //var spacer_elements = YD.getElementsByClassName("breadCrumbTrailSpacer", "span", bc_div);

  var category = document.getElementById("category");
  
  if (category != null){

    var class_list = category.classList;
    console.log("class_list:");
    console.dir(class_list);
    
    for (i=0; i<class_list.length; i++){
      //console.log("t: " + i + " " + class_list[i]);
      if(class_list[i].substring(12,0) == "subcategory_"){
        subcategory_name = class_list[i].substring(12);
        //console.log("subcategory: " + subcategory_name);
      }
    }
  }
  */

  var jq_category = $('#category');
  if (jq_category.hasClass('subcategory')){
    //console.log("we found a sub category");
    var jq_class = jq_category.attr('class');
    //console.log(jq_class);
    //get the subcategory name of the accoring class
    var subcat_start_idx = jq_class.indexOf("subcategory_");
    jq_class = jq_class.substring(subcat_start_idx);
    //console.log(jq_class);
    var subcat_end_idx = jq_class.indexOf(" ");
    jq_class = jq_class.substring(0, subcat_end_idx);
    //console.log(jq_class);
    jq_class = jq_class.substring(12);
    //console.log(jq_class);
    
    subcategory_name = jq_class;
  }


  return(subcategory_name);
}
//**************************************************
//*** end of swGetCurrSubCategory
//**************************************************


//**************************************************
//*** swIsCategoryRelevantForSorting
//***
//*** finds out if the given category name
//*** is relevant for sorting
//**************************************************
function swIsCategoryRelevantForSorting(category_name, subcategory_name){
  
  var is_relevant = false;
  
  //relevant (sub)categories are set hard coded in swSortConstants.relevantCategories
  for (idx in swSortConstants.relevantCategories){
    //console.log(idx);
    
    var cat = "no category";
    var subcat = "";
    
    if (swSortConstants.relevantCategories[idx].category != null){
      cat = swSortConstants.relevantCategories[idx].category;
    } else {
      console.log("error: for " + idx + " the key 'category' is not defined.");
    }
    
    if (swSortConstants.relevantCategories[idx].subcategory != null){
      subcat = swSortConstants.relevantCategories[idx].subcategory;
    }
    //console.log("cat: " + cat);
    //console.log("subcat: " + subcat);
    
    
    if (cat == category_name){
      
      if (subcat == subcategory_name){
      
        is_relevant = true;
      
      }
    }
  }

  return(is_relevant);
}
//**************************************************
//*** end of swIsCategoryRelevantForSorting
//**************************************************



//**************************************************
//*** swGetSubCategoriesByCategory
//***
//*** returns the IDs of the subcategories by
//*** a given category
//**************************************************
function swGetSubCategoriesByCategory(category_name){
  
  var miniBox_navs = $('#category > #subcategoriesBox > .boxBottom > .miniBox > #albumTitle_ > .nav');
  
  var subcats = new Object();
  
  var subcats_length = 0;
  
  for(i=0; i<miniBox_navs.length; i++){
    var curr_nav = miniBox_navs[i];
    var curr_href = curr_nav.getAttribute("href");
    //console.log(curr_href);
    
    //extract the end of the link because we see this as subcat_id
    var last_slash_index = curr_href.lastIndexOf("/");
    var subcat_id = curr_href.substring(last_slash_index + 1);
    
    //console.log(subcat_id);
    subcats[i] = subcat_id;
    
    subcats_length++;
  }
  
  //set length into subcats object
  subcats.length = subcats_length;
  
  return(subcats);
}
//**************************************************
//*** end of swIsCategoryRelevantForSorting
//**************************************************



//**************************************************
//*** swHideEmptySections
//***
//*** this function iterates over the sections
//*** and hides the empty ones.
//**************************************************
function swHideEmptySections(){

  var sections = $('#sectionBox > #sectionBoxBottom > .section');
  
  for (i=0; i<sections.length; i++){
  
    var curr_section = $(sections[i]);
    
    //check if the section contains miniBoxes
    var curr_miniBoxes = curr_section.find('.miniBox');
    
    //console.log(curr_miniBoxes.length);
    if (curr_miniBoxes.length == 0){
      if (swSortConstants.verbose == true){
        console.log("info: hiding section " + sections[i].id + " because it is empty.");
      }
      curr_section.hide();
    }
  
  }

}
//**************************************************
//*** end of swHideEmptySections
//**************************************************


//**************************************************
//*** swHideOriginalGalleriesBoxIfEmpty
//***
//*** this function hides the original gallery
//*** section if it does not contain miniBoxes
//*** anymore
//**************************************************
function swHideOriginalGalleriesBoxIfEmpty(){

  var galleries_box = $('#galleriesBox');
  
  var gallery_miniBoxes = galleries_box.find('.miniBox');
  
  if (gallery_miniBoxes.length == 0){
    
    if (swSortConstants.verbose == true){
      console.log("info: hiding original galleriesBox because it is empty.");
    }
    galleries_box.hide();
  
  }

}
//**************************************************
//*** end of swHideOriginalGalleriesBoxIfEmpty
//**************************************************


//**************************************************
//*** swHideOriginalSubcatBoxIfEmpty
//***
//*** this function hides the original Sub Categories
//*** section if it does not contain miniBoxes
//*** anymore
//**************************************************
function swHideOriginalSubcatBoxIfEmpty(){

  var subcategories_box = $('#subcategoriesBox');
  
  var subcat_miniBoxes = subcategories_box.find('.miniBox');
  
  if (subcat_miniBoxes.length == 0){
    
    if (swSortConstants.verbose == true){
      console.log("info: hiding original subcategoriesBox because it is empty.");
    }
    subcategories_box.hide();
  
  }

}
//**************************************************
//*** end of swHideOriginalSubcatBoxIfEmpty
//**************************************************